﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Sonic.Framework.Tools;
using Sonic.Framework.Interfaces;
using Sonic.Framework.ProcessorToolDirectives;

namespace Sonic.Framework.Site
{
    public class SiteDirectory
    {
        public List<Exclusion> Exclusions = new List<Exclusion>();
        public List<Concatenation> Concatenations = new List<Concatenation>();

        public string RelativePath
        {
            get;
            set;
        }

        public DirectoryInfo DirectoryInfo
        {
            get;
            set;
        }

        public string[] FileExtensions
        {
            get;
            set;
        }

        public IProcessorTool Tool
        {
            get;
            set;
        }

        // ProcessorToolDirectives to run pre exec
        public List<IProcessorToolDirective> PreProcessorDirectives = new List<IProcessorToolDirective>();

        // ProcessorToolDirectives to run post exec
        public List<IProcessorToolDirective> PostProcessorDirectives = new List<IProcessorToolDirective>();


        public SiteDirectory() { }


        public List<FileInfo> GetMatchingFiles(Enums.ExclusionType excludeType)
        {
            NLogSingleton.Instance.Logger.Debug("Getting matching files for " + this.RelativePath + ", excluding " + Enum.GetName(typeof(Enums.ExclusionType), excludeType));

            List<FileInfo> matchingFileInfos = new List<FileInfo>();

            // Get all files that match the extensions configured for this directory
            foreach (string fileExtension in FileExtensions)
            {
                matchingFileInfos.AddRange(DirectoryInfo.GetFiles(fileExtension, SearchOption.AllDirectories));
            }

            // Remove explicitly excluded files
            foreach (Site.Exclusion exclusion in Exclusions)
            {
                if (exclusion.Type != excludeType)
                {
                    foreach (Site.SitePath path in exclusion.Paths)
                    {
                        // Exhaustive search of matched file list to remove unwated file info's
                        foreach (FileInfo matchedFileInfo in matchingFileInfos)
                        {
                            if (matchedFileInfo.FullName == path.FileInfo.FullName)
                            {
                                NLogSingleton.Instance.Logger.Trace("Excluding file " + path.FileInfo.FullName);

                                matchingFileInfos.Remove(path.FileInfo);
                            }
                        }
                    }
                }
            }

            return matchingFileInfos;
        }
    }
}
